package com.graduationproject.filter;

import com.graduationproject.Util.Jwt;
import com.graduationproject.Util.RedisUtil;
import com.graduationproject.config.DBUserDetailsManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * TODO 一、JWT身份验证过滤器
 *
 * @author ss_419
 * @version 1.0
 * @date 2023/3/3 10:56
 */
@Component
// 使用final，将服务注入class
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {
    /**
     * 需要每次收到请求的时候，过滤器都处于活动状态
     * 因此每次用户发送请求时希望过滤器被触发并完成要做的所有工作
     */
    @Autowired
    private final Jwt jwtService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DBUserDetailsManager userDetailsService;
    /**
     * 总体流程：
     * 如果我们有我们的用户电子邮箱并且用户未通过身份验证，我们会从数据库中获取用户详细信息（loadUserByUsername --> UserDetails）
     * 然后我们需要做的是检查用户是否有效，如果用户和令牌有效，我们创建一个UsernamePasswordAuthenticationToken对象，传递UserDetails & 凭证 & 权限信息
     * 扩展上面生成的authToken，包含我们请求的详细信息，然后更新安全上下文中的身份验证令牌
     * 最后一步执行过滤器chain，别忘记放行
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        String path = request.getServletPath();
        // 从请求头中获取认证信息
        String token = request.getHeader("token");
        // 跳过登录和登出路径
        if ("/api/user/login".equals(path)){
            if(token != null) {
                token = token.substring(7); // 去掉"Bearer "前缀
                String username = jwtService.getUsernameFromToken(token);
                String o = (String)redisUtil.get(username);
                if(!o.equals(null)) {
                    throw new RuntimeException("当前账号已经被登录");
                }
            }else {
                filterChain.doFilter(request, response);
                return;
            }

        }else if("/api/user/logout".equals(path)) {
            token = token.substring(7); // 去掉"Bearer "前缀
            String username = jwtService.getUsernameFromToken(token);
            redisUtil.del(username);
            filterChain.doFilter(request, response);
            return;
        }

        final String username;
        if (token == null  || !token.startsWith("Bearer ")) {
            // 如果没有token，直接返回未授权
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未提供认证令牌");
            return;
        }
        // 从token中解析出username
        token = token.substring(7); // 去掉"Bearer "前缀
        username = jwtService.getUsernameFromToken(token);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 从数据库或其他存储加载用户详细信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            // 验证token是否有效
            if (jwtService.validateToken(token)) {
                // 创建认证对象
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(
                                userDetails,
                                null,
                                userDetails.getAuthorities());

                // 设置请求详情
                authentication.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request));

                // 将认证对象设置到安全上下文(下一个过滤器就是检查上下文的,如果没有配置不拦截该路径,那么就一定需要设置上下文)
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }
}
